/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistence;

import Utility.VarcharUpdater;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import logging.CommonsLogging;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import vo.rb_expence;

/**
 *
 * @author Shuhail
 */
public class rb_expence_persist {
    Session sess=null;
    Transaction tx=null;
    
    Logger logger = CommonsLogging.getInstance().getLogger();
    
    public static rb_expence_persist getInstance() {
        return new rb_expence_persist();
    }

    public rb_expence_persist() {
    SessionFactory sf=new Configuration().configure().buildSessionFactory();
    sess=sf.openSession();
    tx=sess.beginTransaction();
    }
    
    public boolean insert(rb_expence expence) {
        
        rb_expence exp =new rb_expence();
        
        exp.setExpence_id(this.getNextPK());
        exp.setExpence_name(expence.getExpence_name());
        exp.setExpence_type(expence.getExpence_type());
        
        
        sess.save(exp);
        tx.commit();
        if(logger.isDebugEnabled()) {
            logger.debug("***Done Insertion***");
        }
        return true;
    }
    
    public List<rb_expence> fetchAll() {
        Query query = sess.getNamedQuery("fetchAllExpenses");
        List<rb_expence> list = query.list();
        return list;
    }
    public List<String> fetchAllExpenceType() {
        List<String> list = new ArrayList<String>();
        Query query = sess.getNamedQuery("fetchAllExpenseType");
        list = query.list();
        return list;
    }
    
    public String getNextPK() {
        
        List list = this.fetchAll();
        List<String> listSt = new ArrayList<String>();
        Iterator it = list.iterator();
        while(it.hasNext()) {
            rb_expence exp = (rb_expence)it.next();
            listSt.add(exp.getExpence_id());
        }
        String lastPK = VarcharUpdater.getInstance().getTheLastPK(listSt);
        return VarcharUpdater.getInstance().getValue(lastPK);
    }
     public static void main(String[] args){
    
         rb_expence exp = new rb_expence();
         exp.setExpence_id("E003");
         exp.setExpence_name("Raw Material Purchase");
         exp.setExpence_type("Daily");
         
         rb_expence_persist rb = rb_expence_persist.getInstance();
         //rb.insert(exp);
         
         System.out.println(new rb_expence_persist().getNextPK());
}
     
}
